import { Math, Scene, Types } from 'phaser';

import { Snake } from '@/pages/game/snake/classes/Snake';
import { Food } from '@/pages/game/snake/classes/Food';

import snake from '../../../../assets/resources/snake/snake.png';
import food from '../../../../assets/resources/snake/food.png';

export const blockSize = 16;
export const gridSize = { x: 50, y: 40 };

const resources = { snake, food };

class SnakeScene extends Scene {
  snake!: Snake;
  food!: Food;
  cursors!: Types.Input.Keyboard.CursorKeys;

  constructor() {
    super('Snake');
  }

  preload() {
    this.load.setBaseURL(window.location.origin);
    Object.keys(resources).forEach(key => this.load.image(key, `${resources[key]}`));
  }

  create() {
    this.snake = new Snake(this, 10, 10, 'snake');
    this.food = new Food(this, 5, 5, 'food');
    this.cursors = this.input.keyboard.createCursorKeys();
  }

  update(time: number) {
    if (!this.snake.alive) {
      return;
    }
    if (this.cursors.left!.isDown) {
      this.snake.faceLeft();
    } else if (this.cursors.right!.isDown) {
      this.snake.faceRight();
    } else if (this.cursors.up!.isDown) {
      this.snake.faceUp();
    } else if (this.cursors.down!.isDown) {
      this.snake.faceDown();
    }
    if (this.snake.update(time)) {
      if (this.snake.collideWithFood(this.food)) {
        this.repositionFood();
      }
    }
  }

  repositionFood() {
    const testGrid: boolean[][] = [];
    for (let y = 0; y < gridSize.y; y++) {
      testGrid[y] = [];
      for (let x = 0; x < gridSize.x; x++) {
        testGrid[y][x] = true;
      }
    }

    this.snake.updateGrid(testGrid);

    const validLocations: { x: number; y: number }[] = [];
    for (let y = 0; y < gridSize.y; y++) {
      for (let x = 0; x < gridSize.x; x++) {
        if (testGrid[y][x]) {
          validLocations.push({ x, y });
        }
      }
    }

    if (validLocations.length > 0) {
      const pos = Math.RND.pick(validLocations);
      this.food.setPosition(pos.x * blockSize, pos.y * blockSize);
      return true;
    }
    return false;
  }
}

export default SnakeScene;
